package com.xuecheng.content.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xuecheng.basic.api.BasicClient;
import com.xuecheng.commons.constants.CourseConstants;
import com.xuecheng.commons.enums.ErrorCode;
import com.xuecheng.commons.model.vo.CategoryVo;
import com.xuecheng.commons.model.vo.ResponseResult;
import com.xuecheng.commons.model.vo.TeachplanVo;
import com.xuecheng.commons.utils.BeanHelper;
import com.xuecheng.content.config.MinioProperties;
import com.xuecheng.content.domain.CourseBase;
import com.xuecheng.content.domain.CoursePub;
import com.xuecheng.content.mappers.CoursePubMapper;
import com.xuecheng.content.service.CourseBaseService;
import com.xuecheng.content.service.CoursePubService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xuecheng.content.service.TeachplanService;
import com.xuecheng.web.exceptions.BusinessException;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 课程发布 服务实现类
 * </p>
 *
 * @author itheima
 * @since 2022-09-17
 */
@Service
public class CoursePubServiceImpl extends ServiceImpl<CoursePubMapper, CoursePub> implements CoursePubService {
    @Autowired
    private CourseBaseService courseBaseService;
    @Autowired
    private TeachplanService teachplanService;
    @Autowired
    private BasicClient basicClient;
    @Autowired
    private Configuration configuration;
    @Autowired
    private MinioClient minioClient;
    @Autowired
    private MinioProperties prop;
    @Autowired
    private PublishHtmlService publishHtmlService;
    @Autowired
    private RabbitTemplate rabbitTemplate;
    //课程预览
    @Override
    public Map<String, Object> preview(Long courseBaseId) {
        //1.查询课程数据
        CourseBase courseBase = courseBaseService.getById(courseBaseId);
        //2.查询课程计划数据
        ResponseResult<TeachplanVo> treeNodes = teachplanService.treeNodes(courseBaseId);
        TeachplanVo vo = treeNodes.getData();
        //3.查询教师数据(略)
        //4.调用Feign接口查询课程分类名称
        String StName = getCategoryName(courseBase.getSt());
        String MtName = getCategoryName(courseBase.getMt());
        //5.构造CoursePub对象
        CoursePub coursePub = BeanHelper.copyProperties(courseBase, CoursePub.class);
        coursePub.setId(null);
        coursePub.setCourseId(courseBaseId);
        //设置分类名称
        coursePub.setMtName(MtName);
        coursePub.setStName(StName);
        //设置课程计划
        coursePub.setTeachplan(JSON.toJSONString(vo));
        //6.将对象放入map返回
        HashMap<String, Object> map = new HashMap<>();
        map.put("coursePub", coursePub);
        map.put("teachplanNode",vo);
        return map;
    }
    //获取分类名称
    private String getCategoryName(String id) {
        ResponseResult<CategoryVo> result = basicClient.findById(id);
        CategoryVo data = result.getData();
        return data.getName();
    }
    //课程发布
    @Override
    public ResponseResult publish(Long courseBaseId) throws Exception{
        //A.保存课程发布数据到数据库
        //1.根据courseId查询课程数据（修改审核状态时需要用到）
        CourseBase courseBase = courseBaseService.getById(courseBaseId);
        //2.根据courseId获取课程发布数据
        Map<String, Object> map = preview(courseBaseId);
        CoursePub coursePub =(CoursePub) map.get("coursePub");
        //3.查询课程发布表中是否已经存在这条数据
        LambdaQueryWrapper<CoursePub> wq = new LambdaQueryWrapper<>();
        wq.eq(CoursePub::getCourseId, courseBaseId);
        CoursePub pub = this.getOne(wq);
        boolean flag=false;
        if (pub == null) {
            //不存在：保存
            flag = this.save(coursePub);
        } else {
            //存在：更新
            coursePub.setId(pub.getId());
            flag=this.updateById(coursePub);
        }
        if (!flag) {
            throw new BusinessException(ErrorCode.ERROR);
        }
        //4.更新课程审核状态
        courseBase.setAuditStatus(CourseConstants.AUDIT_PUBLISHED_STATUS);
        courseBaseService.updateById(courseBase);

        //B.生成静态页面，保存minio
        try {
            publishHtmlService.publish(map, coursePub.getId());
        } catch (Exception e) {
            e.printStackTrace();
        }
        //C.发送MQ消息
        rabbitTemplate.convertAndSend(
                "content-exchange",
                "course.pub",
                coursePub.getId());//交换机，路由key，消息内容

        return ResponseResult.okResult();
    }


}
